import { Class } from '../models/Class.js';
import { Student } from '../models/Student.js';
import { Teacher } from '../models/Teacher.js';
import { College } from '../models/College.js';
import fs from 'fs';
import { dataFiles } from '../config/database.js';

export class ClassController {
  constructor() {
    this.classModel = new Class();
    this.studentModel = new Student();
    this.teacherModel = new Teacher();
    this.collegeModel = new College();
  }

  // 获取班级列表
  async getClasses(req, res) {
    try {
      console.log('获取班级列表，查询参数:', req.query);

      const classes = await this.classModel.findAll();
      const students = await this.studentModel.findAll();

      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;

      // 应用搜索过滤
      let filteredClasses = [...classes];

      // 按班级名称筛选
      if (req.query.className && req.query.className.trim() !== '') {
        const className = req.query.className.trim();
        const beforeCount = filteredClasses.length;
        filteredClasses = filteredClasses.filter(cls =>
          cls.className === className
        );
        console.log('按班级名称筛选:', className, '筛选前:', beforeCount, '筛选后:', filteredClasses.length);
      }

      // 按学院筛选
      if (req.query.department && req.query.department.trim() !== '') {
        const department = req.query.department.trim();
        const beforeCount = filteredClasses.length;
        filteredClasses = filteredClasses.filter(cls =>
          cls.department === department
        );
        console.log('按学院筛选:', department, '筛选前:', beforeCount, '筛选后:', filteredClasses.length);
      }

      // 如果同时选择了班级名称和学院，则两个条件都要满足（AND关系）
      console.log('最终筛选结果数量:', filteredClasses.length, '筛选条件:', {
        className: req.query.className || '未选择',
        department: req.query.department || '未选择'
      });

      // 关联学生数据
      const classesWithRealStudentCount = filteredClasses.map(cls => {
        const classStudents = students.filter(student =>
          student.className === cls.className
        );

        return {
          ...cls,
          studentCount: classStudents.length,
          actualStudents: classStudents,
          originalStudentCount: cls.studentCount
        };
      });

      // 分页
      const paginatedClasses = classesWithRealStudentCount.slice(startIndex, endIndex);

      // 构建响应
      const response = {
        data: paginatedClasses,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: classesWithRealStudentCount.length,
          totalPages: Math.ceil(classesWithRealStudentCount.length / pageSize)
        }
      };

      console.log('返回班级数据:', {
        dataCount: paginatedClasses.length,
        total: classesWithRealStudentCount.length
      });

      res.json(response);
    } catch (error) {
      console.error('获取班级列表失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 获取带学生信息的班级列表（用于成绩管理）
  async getClassesWithStudents(req, res) {
    try {
      console.log('获取带学生信息的班级列表');
      const classes = await this.classModel.findAll();
      const students = await this.studentModel.findAll();

      // 为每个班级添加学生信息
      const classesWithStudents = classes.map(classItem => {
        const classStudents = students.filter(student =>
          student.className === classItem.className
        );

        return {
          ...classItem,
          studentCount: classStudents.length,
          actualStudentCount: classStudents.length,
          students: classStudents
        };
      });

      console.log(`返回 ${classesWithStudents.length} 个班级数据`);
      res.json(classesWithStudents);
    } catch (error) {
      console.error('获取班级列表失败:', error);
      res.status(500).json({
        error: '获取班级列表失败',
        details: error.message
      });
    }
  }

  // 获取班级选项数据
  async getClassOptions(req, res) {
    try {
      const classes = await this.classModel.findAll();
      const students = await this.studentModel.findAll();
      const teachers = await this.teacherModel.findAll();
      const colleges = await this.collegeModel.findAll();

      // 从学院数据中获取学院列表（只获取状态为active的学院）
      const departments = colleges
        .filter(c => c.status === 'active')
        .map(c => c.name)
        .filter(Boolean)
        .sort(); // 按字母顺序排序

      console.log('获取学院列表:', {
        totalColleges: colleges.length,
        activeColleges: colleges.filter(c => c.status === 'active').length,
        departmentNames: departments,
        departmentNamesCount: departments.length
      });

      // 从教师数据中获取讲师列表（只获取状态为active的教师）
      console.log('所有教师数据:', JSON.stringify(teachers, null, 2));

      const activeTeachers = teachers.filter(t => {
        const isActive = t.status === 'active';
        const hasName = t.name && t.name.trim() !== '';
        console.log(`教师 ${t.id}: name="${t.name}", status="${t.status}", isActive=${isActive}, hasName=${hasName}`);
        return isActive && hasName;
      });

      const lecturers = activeTeachers
        .map(t => t.name.trim())
        .filter(name => name !== '') // 确保不是空字符串
        .filter((name, index, self) => self.indexOf(name) === index) // 去重
        .sort(); // 按字母顺序排序

      console.log('获取讲师列表:', {
        totalTeachers: teachers.length,
        activeTeachers: activeTeachers.length,
        lecturerNames: lecturers,
        lecturerNamesCount: lecturers.length
      });

      // 处理导员数据
      let counselors = [...new Set(classes.map(c => c.counselor).filter(Boolean))];

      // 尝试从专门的导员数据文件中读取
      try {
        if (fs.existsSync(dataFiles.counselors)) {
          const counselorsData = JSON.parse(fs.readFileSync(dataFiles.counselors, 'utf8'));
          const counselorNames = counselorsData.map(c => c.name).filter(Boolean);
          // 合并现有导员和文件中的导员
          counselors = [...new Set([...counselors, ...counselorNames])];
        } else {
          // 如果导员文件不存在，创建默认的导员数据文件
          const defaultCounselors = [
            { id: 1, name: '王导员', employeeId: 'C1001', department: '计算机学院', status: 'active' },
            { id: 2, name: '刘导员', employeeId: 'C1002', department: '软件学院', status: 'active' },
            { id: 3, name: '陈导员', employeeId: 'C1003', department: '电子信息学院', status: 'active' },
            { id: 4, name: '张导员', employeeId: 'C1004', department: '计算机学院', status: 'active' },
            { id: 5, name: '李导员', employeeId: 'C1005', department: '软件学院', status: 'active' }
          ];

          // 确保所有现有班级中的导员都在默认数据中
          counselors.forEach(counselorName => {
            if (!defaultCounselors.some(c => c.name === counselorName)) {
              defaultCounselors.push({
                id: defaultCounselors.length + 1,
                name: counselorName,
                employeeId: `C${1000 + defaultCounselors.length + 1}`,
                department: '未知学院',
                status: 'active'
              });
            }
          });

          fs.writeFileSync(dataFiles.counselors, JSON.stringify(defaultCounselors, null, 2));
          console.log('创建默认导员数据文件');

          // 更新导员列表为完整列表
          counselors = defaultCounselors.map(c => c.name);
        }
      } catch (error) {
        console.error('处理导员数据失败:', error);
        // 如果出错，继续使用从班级中提取的导员数据
      }

      const response = {
        departments,
        majors: [], // 保留字段以兼容前端，但返回空数组
        lecturers,
        counselors,
        grades: [] // 保留字段以兼容前端，但返回空数组
      };

      console.log('返回班级选项数据:', {
        departments: response.departments.length,
        lecturers: response.lecturers.length,
        lecturersList: response.lecturers,
        counselors: response.counselors.length
      });

      res.json(response);
    } catch (error) {
      console.error('获取班级选项失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 获取班级统计信息
  async getClassStats(req, res) {
    try {
      const classes = await this.classModel.findAll();
      const students = await this.studentModel.findAll();

      const totalClasses = classes.length;
      let totalStudents = 0;
      let activeClasses = 0;

      classes.forEach(cls => {
        const classStudents = students.filter(student =>
          student.className === cls.className
        );
        totalStudents += classStudents.length;
      });

      const averageStudents = totalClasses > 0 ? Math.round(totalStudents / totalClasses) : 0;

      res.json({
        totalClasses,
        totalStudents,
        activeClasses: totalClasses, // 所有班级都视为活跃
        averageStudents
      });
    } catch (error) {
      console.error('获取班级统计失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 更新导员数据文件
  async updateCounselorData(counselorName, department) {
    try {
      if (!counselorName) return;

      let counselors = [];

      // 读取现有导员数据
      if (fs.existsSync(dataFiles.counselors)) {
        counselors = JSON.parse(fs.readFileSync(dataFiles.counselors, 'utf8'));
      }

      // 检查导员是否已存在
      const existingCounselor = counselors.find(c => c.name === counselorName);

      if (!existingCounselor) {
        // 添加新导员
        const newCounselor = {
          id: counselors.length > 0 ? Math.max(...counselors.map(c => c.id)) + 1 : 1,
          name: counselorName,
          employeeId: `C${1000 + counselors.length + 1}`,
          department: department || '未知学院',
          status: 'active',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        };

        counselors.push(newCounselor);
        fs.writeFileSync(dataFiles.counselors, JSON.stringify(counselors, null, 2));
        console.log('添加新导员:', newCounselor);
      } else if (department && existingCounselor.department === '未知学院') {
        // 更新现有导员的部门信息
        existingCounselor.department = department;
        existingCounselor.updatedAt = new Date().toISOString();
        fs.writeFileSync(dataFiles.counselors, JSON.stringify(counselors, null, 2));
        console.log('更新导员部门信息:', existingCounselor);
      }
    } catch (error) {
      console.error('更新导员数据失败:', error);
    }
  }

  // 创建班级
  async createClass(req, res) {
    try {
      const {
        className,
        lecturer,
        counselor,
        department,
        classroom
      } = req.body;

      console.log('创建班级:', { className, lecturer, counselor });

      if (!className) {
        return res.status(400).json({ error: '班级名称为必填字段' });
      }

      const newClass = {
        className,
        lecturer: lecturer || '',
        counselor: counselor || '',
        department: department || '',
        classroom: classroom || ''
      };

      const createdClass = await this.classModel.create(newClass);

      // 更新导员数据
      if (counselor) {
        await this.updateCounselorData(counselor, department);
      }

      if (createdClass) {
        console.log('创建班级成功:', createdClass);
        res.status(201).json(createdClass);
      } else {
        res.status(500).json({ error: '保存失败' });
      }
    } catch (error) {
      console.error('创建班级失败:', error);
      res.status(500).json({ error: '创建失败' });
    }
  }

  // 更新班级
  async updateClass(req, res) {
    try {
      const { id } = req.params;
      const {
        className,
        lecturer,
        counselor,
        department,
        classroom
      } = req.body;

      console.log('更新班级:', id, { className, counselor });

      const updatedClass = await this.classModel.update(parseInt(id), {
        className,
        lecturer: lecturer || '',
        counselor: counselor || '',
        department: department || '',
        classroom: classroom || ''
      });

      // 更新导员数据
      if (counselor && updatedClass) {
        await this.updateCounselorData(counselor, department);
      }

      if (updatedClass) {
        console.log('更新班级成功:', updatedClass);
        res.json(updatedClass);
      } else {
        res.status(404).json({ error: '班级不存在' });
      }
    } catch (error) {
      console.error('更新班级失败:', error);
      res.status(500).json({ error: '更新失败' });
    }
  }

  // 删除班级
  async deleteClass(req, res) {
    try {
      const { id } = req.params;
      console.log('删除班级，ID:', id);

      const classItem = await this.classModel.findById(parseInt(id));
      if (!classItem) {
        console.log('班级不存在，ID:', id);
        return res.status(404).json({
          error: '班级不存在',
          message: '班级不存在'
        });
      }

      console.log('查找班级关联的学生，班级名称:', classItem.className);
      const students = await this.studentModel.findAll();
      const relatedStudents = students.filter(student => student.className === classItem.className);

      console.log(`找到 ${relatedStudents.length} 名关联学生`);

      if (relatedStudents.length > 0) {
        console.log('无法删除，存在关联学生:', {
          className: classItem.className,
          studentCount: relatedStudents.length,
          studentIds: relatedStudents.map(s => s.id)
        });
        return res.status(400).json({
          error: `无法删除班级 "${classItem.className}"，该班级下还有 ${relatedStudents.length} 名学生。请先处理这些学生后再删除班级。`,
          message: `无法删除，该班级下还有 ${relatedStudents.length} 名学生`,
          studentCount: relatedStudents.length
        });
      }

      console.log('开始删除班级，ID:', id, '班级名称:', classItem.className);
      const success = await this.classModel.delete(parseInt(id));

      if (success) {
        console.log('删除班级成功:', classItem.className);
        res.json({
          message: '删除成功',
          success: true
        });
      } else {
        console.error('删除操作返回false，班级ID:', id);
        res.status(500).json({
          error: '删除失败，请稍后重试',
          message: '删除失败'
        });
      }
    } catch (error) {
      console.error('删除班级失败，错误详情:', error);
      console.error('错误堆栈:', error.stack);
      res.status(500).json({
        error: '删除失败：' + (error.message || '未知错误'),
        message: '删除失败'
      });
    }
  }

  // 获取指定班级的学生列表（用于点名）
  async getClassStudents(req, res) {
    try {
      const { className } = req.params;
      const decoded = decodeURIComponent(className);
      const students = await this.studentModel.findAll();
      const classStudents = students.filter(s => s.className === decoded);
      res.json(classStudents);
    } catch (error) {
      console.error('获取班级学生失败:', error);
      res.status(500).json({ error: '获取班级学生失败' });
    }
  }
}
